#include "sr.h"

static int state;
static char inEmMode;
static int count;

#define READY 1
#define RUNNING 2

void
initBrakeCondition(void ) {
    state = READY;
    inEmMode = 1;
    count = 0;
}

void
brakeConditionFire(double vc, char *brake, int hasEventFlags, int *craneKnownFlags, int *cranePresentFlags) {

    if(GET_BIT(*craneKnownFlags, EMMODECHECKALFABIT)) {
        if(GET_BIT(*cranePresentFlags, EMMODECHECKALFABIT)) {
            inEmMode = 1;
        }
    }

    if(state == RUNNING) {
        if(GET_BIT(*craneKnownFlags, VCCONTROLALGBIT)) {
            if(GET_BIT(*cranePresentFlags, VCCONTROLALGBIT)) {
                if(vc < 0.01 || vc > -0.01) {
                    count++;
                }
                else {
                    count = 0;
                }

                if(inEmMode == 1) {
                    if(count == 7500) {
                        *brake = 1;
                        SET_BIT_TRUE(*craneKnownFlags, BRAKECONDITIONBIT);
                        SET_BIT_TRUE(*cranePresentFlags, BRAKECONDITIONBIT);
                        count = 0;
                    }
                }
                else {
                    if(count == 2500) {
                        *brake = 1;
                        SET_BIT_TRUE(*craneKnownFlags, BRAKECONDITIONBIT);
                        SET_BIT_TRUE(*cranePresentFlags, BRAKECONDITIONBIT);
                        count = 0;
                    }
                }
            }
        }
    }

    if(GET_BIT(*craneKnownFlags, VCCONTROLALGBIT) && 
        GET_BIT(*craneKnownFlags, EMMODECHECKALFABIT) &&
        !GET_BIT(*craneKnownFlags, BRAKECONDITIONBIT)) {

        SET_BIT_TRUE(*craneKnownFlags, BRAKECONDITIONBIT);
    }
}

void
brakeConditionPostfire(int hasEventFlags, int craneKnownFlags, int cranePresentFlags) {

    switch(state) {
        case READY: {
            if(GET_BIT(craneKnownFlags, TRIGGERBIT)) {
                if(GET_BIT(cranePresentFlags, TRIGGERBIT)) {
                    state = RUNNING;
                }
            }
        } break;

        case RUNNING: {
            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                initBrakeCondition();
                break;
            }

            if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                    initBrakeCondition();
                }
            }
        }
    }
}
